﻿using ch02.binary.module;
using ch02.binary.type;

namespace ch02.binary.wasm_reader
{
    public partial struct WasmReader
    {
        // type sec
        private FuncType[] ReadTypeSec()
        {
            var vec = new FuncType[ReadVarU32()];
            for (var i = 0; i < vec.Length; i++)
            {
                vec[i] = ReadFuncType();
            }

            return vec;
        }

        // entity types
        private FuncType ReadFuncType()
        {
            var ft = new FuncType
            {
                Tag = ReadByte(),
                ParamTypes = ReadValTypes(),
                ResultTypes = ReadValTypes(),
            };
            if (ft.Tag != ConstData.FtTag)
            {
                Panic.Run("invalid functype tag: %d", ft.Tag);
            }

            return ft;
        }
        
        // value types
        private ValType[] ReadValTypes()
        {
            var vec = new ValType[ReadVarU32()];
            for (var i = 0; i < vec.Length; i++)
            {
                vec[i] = ReadValType();
            }

            return vec;
        }

        private ValType ReadValType()
        {
            var vt = (ValType) ReadByte();
            switch (vt)
            {
                case ValType.ValTypeI32:
                case ValType.ValTypeI64:
                case ValType.ValTypeF32:
                case ValType.ValTypeF64:
                    return vt;
                default:
                    Panic.Run("malformed value type: %d", vt);
                    break;
            }

            return vt;
        }

    }
}